package com.work.studio.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.work.studio.R;
import com.work.studio.entitys.CustomerSignEntity;
import com.work.studio.utils.GlideUtils;
import com.work.studio.utils.TimerUtils;

import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainView extends FrameLayout {

    private Context mContext;
    private MapView mapView;//地图
    private TextView ymrValue;//年月日
    private TextView weekValue;//星期
    private TextView timeValue;//时间
    private String TAG = this.getClass().getSimpleName();
    private AMap aMap;
    private View infoWindow = null;

    public MainView(@NonNull Context context) {
        this(context, null);
    }

    public MainView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MainView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.view_main_content, null);
        addView(view);
        ymrValue = view.findViewById(R.id.ymr_value);
        weekValue = view.findViewById(R.id.week_value);
        timeValue = view.findViewById(R.id.time_value);
        mapView = view.findViewById(R.id.map_view);

        initMap();
    }

    private void initMap() {
        try {
            if (aMap == null) {
                aMap = mapView.getMap();
            }
            aMap.clear();

//            aMap.setInfoWindowAdapter(this);
            aMap.setMapType(AMap.MAP_TYPE_NIGHT);////夜景地图
            //导航地图
//            aMap.setMapType(AMap.MAP_TYPE_NAVI);
            //车路线地图
//            aMap.setMapType(AMap.MAP_TYPE_BUS);
            //显示实时交通状况
            aMap.setTrafficEnabled(true);
            //显示3D楼块
            aMap.showBuildings(true);
            //显示底图文字
//            aMap.showMapText(((CheckBox) view).isChecked());
            //标准地图
//            aMap.setMapType(AMap.MAP_TYPE_NORMAL);
            //卫星地图
//            aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
            aMap.setOnMarkerClickListener(null);

            UiSettings uiSettings = aMap.getUiSettings();
//                uiSettings.setMyLocationButtonEnabled(true);//设置定位按钮是否可见。
            uiSettings.setZoomControlsEnabled(false);//设置缩放按钮是否可见。
            uiSettings.setLogoBottomMargin(-50);//设置Logo下边界距离屏幕底部的边距(隐藏logo)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onCreate(Bundle savedInstanceState) {

        mapView.onCreate(savedInstanceState);
    }

    public void onDestroy() {
        mapView.onDestroy();
    }

    public void onResume() {
        mapView.onResume();
    }

    public void init() {
        ymrValue.setText(TimerUtils.getCurrentYMD());
        weekValue.setText(TimerUtils.StringDataWeek(new Date()));
        timeValue.setText(TimerUtils.getCurrentHMSTime());
    }

    public void onPause() {
        mapView.onPause();
    }

    public void onSaveInstanceState(Bundle outState) {
        mapView.onSaveInstanceState(outState);
    }


    private void startGrowAnimation(Marker marker) {

        if (marker != null) {
            Animation animation = new ScaleAnimation(0, 1, 0, 1);
            animation.setInterpolator(new LinearInterpolator());
            //整个移动所需要的时间
            animation.setDuration(1000);
            animation.setFillMode(1);//动画保存之前的状态为1 之后为0
            //设置动画
            marker.setAnimation(animation);
            //开始动画
            marker.startAnimation();
            marker.showInfoWindow();
        }
    }


    public BitmapDescriptor getBitmap(CustomerSignEntity.CustomerReturnListBean latLng) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_info_widow_view, null);

        TextView nameValue = view.findViewById(R.id.name_value);
        TextView timeValue = view.findViewById(R.id.time_value);
        TextView addressValue = view.findViewById(R.id.address_value);
        ImageView headValue = view.findViewById(R.id.head_value);

        nameValue.setText(""+latLng.getUserName());
        timeValue.setText(""+latLng.getSignTime());
        addressValue.setText(""+latLng.getAddress());
        if (latLng.getSex() == 1) {
            headValue.setImageResource(R.drawable.man);
        } else {
            headValue.setImageResource(R.drawable.woman);
        }

        return BitmapDescriptorFactory.fromView(view);
    }

    public BitmapDescriptor getBitmap(CustomerSignEntity.CustomerReturnListBean latLng, Bitmap bitmap) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_info_widow_view, null);

        TextView nameValue = view.findViewById(R.id.name_value);
        TextView timeValue = view.findViewById(R.id.time_value);
        TextView addressValue = view.findViewById(R.id.address_value);
        ImageView headValue = view.findViewById(R.id.head_value);

        nameValue.setText(""+latLng.getUserName());
        timeValue.setText(""+latLng.getSignTime());
        addressValue.setText(""+latLng.getAddress());

        if (bitmap != null && !bitmap.isRecycled()) {
            headValue.setImageBitmap(bitmap);
        } else {
            if (latLng.getSex() == 1) {
                headValue.setImageResource(R.drawable.man);
            } else {
                headValue.setImageResource(R.drawable.woman);
            }
        }

        return BitmapDescriptorFactory.fromView(view);
    }

    public void setDatas(List<CustomerSignEntity.CustomerReturnListBean> customerReturnList) {

        try {



            initMap();

            if (customerReturnList == null || customerReturnList.size() <=0) {
                return;
            }

            Observable.create(new ObservableOnSubscribe<MarkerOptions>() {

                @Override
                public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<MarkerOptions> emitter) throws Exception {


                    for (CustomerSignEntity.CustomerReturnListBean customerReturnListBean : customerReturnList) {


                        List<CustomerSignEntity.CustomerReturnListBean.UserHeadListBean> imageList = customerReturnListBean.getUserHeadList();

                        String path = "";
                        if (imageList != null && imageList.size() > 0) {
                            path = imageList.get(0).getResourceUrl();
                        }

                        if (!TextUtils.isEmpty(path)) {

                            Glide.with(mContext)
                                    .asBitmap()
                                    .load(path)
//                                    .error(R.drawable.default_image)
//                                    .placeholder(R.drawable.default_image)
                                    .into(new CustomTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {


                                            MarkerOptions markerOptions = new MarkerOptions();
                                            LatLng latLng = new LatLng(customerReturnListBean.getLat(), customerReturnListBean.getLng());
                                            markerOptions.position(latLng);

                                            markerOptions.icon(getBitmap(customerReturnListBean, resource));
//                                          markerOptions.title("我是标题").snippet("对应的内容对应的内容对应的内容");
                                            markerOptions.draggable(true);//设置Marker可拖动
                                            markerOptions.setFlat(true);//设置marker平贴地图效果

                                            emitter.onNext(markerOptions);

                                        }

                                        @Override
                                        public void onLoadCleared(@Nullable Drawable placeholder) {

                                        }
                                    });
                        } else {

//                        GlideUtils.getBitmap(customerReturnListBean.get)

                            MarkerOptions markerOptions = new MarkerOptions();
                            LatLng latLng = new LatLng(customerReturnListBean.getLat(), customerReturnListBean.getLng());
                            markerOptions.position(latLng);

                            markerOptions.icon(getBitmap(customerReturnListBean));
//                    markerOptions.title("我是标题").snippet("对应的内容对应的内容对应的内容");
                            markerOptions.draggable(true);//设置Marker可拖动
                            markerOptions.setFlat(true);//设置marker平贴地图效果

                            emitter.onNext(markerOptions);
                        }


                    }

                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<MarkerOptions>() {
                        @Override
                        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.annotations.NonNull MarkerOptions markerOptions) {

                            try {

                                if (aMap == null) {
                                    aMap = mapView.getMap();
                                }

                                Marker growMarker = aMap.addMarker(markerOptions);
                                growMarker.setClickable(true); //marker 设置是否可点击
                                startGrowAnimation(growMarker);
                                growMarker.showInfoWindow();
                                Log.e(TAG, "onNext");

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(@io.reactivex.annotations.NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();//存放所有点的经纬度
                            for (CustomerSignEntity.CustomerReturnListBean latLng : customerReturnList) {
                                boundsBuilder.include(new LatLng(latLng.getLat(), latLng.getLng()));//把所有点都include进去（LatLng类型）
                            }
                            if (aMap == null) {
                                aMap = mapView.getMap();
                            }
                            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 100));//第二个参数为四周留空宽度
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
